<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="生产计划编号" prop="planSn" label-width="55">
        <el-input
          v-model="queryParams.planSn"
          placeholder="请输入生产计划编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产计划状态" prop="planState" label-width="55">
        <el-input
          v-model="queryParams.planState"
          placeholder="请输入生产计划状态"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['mes:plan:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['mes:plan:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['mes:plan:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:plan:export']"
        >导出</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="planList"  border style="width: 100%" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="序号" align="center" prop="number" width="90"/>
      <el-table-column label="生产计划状态" align="center" prop="planState"width="100" >
        <template v-slot = "scope">
          <dict-tag :options="dict.type.plan_state" :value="scope.row.planState"/>
        </template>
      </el-table-column>
      <el-table-column label="生产计划编号" align="center" prop="planSn" />
      <el-table-column label="订单名称" align="center" prop="orderName" />
      <el-table-column label="订单编号" align="center" prop="orderSn" />
<!--      <el-table-column label="总需求数量" align="center" prop="reqNum" />-->
<!--      <el-table-column label="下达数量" align="center" prop="planNum" />-->
<!--      <el-table-column label="未下达数量" align="center" prop="grNum" />-->
      <el-table-column label="创建者" align="center" prop="createdBy" />
      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:plan:edit']"
          >计划明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mes:plan:remove']"
          >撤回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item>
          <el-divider>产品列表</el-divider><!--分割线-->
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" v-loading="loading" border :data="planProList">
              <el-table-column label="产品名称" prop="proName" align="center">
              </el-table-column>
              <el-table-column label="产品编码" prop="proSn" align="center">
              </el-table-column>
              <el-table-column label="总需求数量" prop="proNum" align="center">
              </el-table-column>
              <el-table-column label="下达数量" prop="releasedNum" align="center">
              </el-table-column>
              <el-table-column label="未下达数量" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.proNum-scope.row.releasedNum}}</span>
                </template>
              </el-table-column>
<!--              <el-table-column label="计划开始日期" prop="planStartDate" width="250px">-->
<!--                <template slot-scope="scope">-->
<!--                  <el-date-picker clearable-->
<!--                                  v-model="scope.row.planStartDate"-->
<!--                                  type="date"-->
<!--                                  value-format="yyyy-MM-dd"-->
<!--                                  placeholder="请选择计划开始日期"-->
<!--                                  :disabled="true">-->
<!--                  </el-date-picker>-->
<!--                </template>-->
<!--              </el-table-column>-->
<!--              <el-table-column label="计划截止日期" prop="planEndDate" width="250px">-->
<!--                <template slot-scope="scope">-->
<!--                  <el-date-picker clearable-->
<!--                                  v-model="scope.row.planEndDate"-->
<!--                                  type="date"-->
<!--                                  value-format="yyyy-MM-dd"-->
<!--                                  placeholder="请选择计划截止日期"-->
<!--                                  :disabled="true">-->
<!--                  </el-date-picker>-->
<!--                </template>-->
<!--              </el-table-column>-->
            </el-table>
          </el-card>
        </el-form-item>

        <el-form-item>
          <el-divider>物料计划下达</el-divider><!--分割线-->
          <el-card shadow="always" style="border-radius: 15px;">
            <el-table style="border-radius: 15px;" border :data="this.PlanList">
              <el-table-column label="状态" prop="state" align="center">
                <template slot-scope="scope">
                  <span>{{buttonMap.get(scope.row.state)}}</span>
                </template>
              </el-table-column>
              <el-table-column label="产品名称" prop="proName" align="center">
                <template slot-scope="scope">
                  <el-select v-if="PlanList[scope.$index].state==0" v-model="scope.row.proId" filterable placeholder="请选择">
                    <el-option
                      v-for="item in planProList"
                      :key="item.proId"
                      :label="item.proName"
                      :value="item.proId">
                    </el-option>
                  </el-select>

                  <el-select v-else v-model="scope.row.proId" :disabled="true" filterable placeholder="请选择">
                    <el-option
                      v-for="item in planProList"
                      :key="item.proId"
                      :label="item.proName"
                      :value="item.proId">
                    </el-option>
                  </el-select>

                </template>
              </el-table-column>
              <el-table-column label="下达数量" prop="grNum" align="center">
                <template slot-scope="scope">
                  <el-input v-if="PlanList[scope.$index].state==0" v-model="scope.row.num" placeholder="请输入下达数量" />

                  <span v-else>{{scope.row.num}}</span>

                </template>
              </el-table-column>
              <el-table-column label="计划开始日期" prop="startDate" align="center">
                <template slot-scope="scope">
                  <el-date-picker v-if="PlanList[scope.$index].state==0"
                                  clearable
                                  v-model="scope.row.startDate"
                                  type="date"
                                  value-format="yyyy-MM-dd"
                                  style="width: 100%;"
                                  placeholder="请选择日期">
                  </el-date-picker>

                  <span v-else>{{scope.row.startDate}}</span>

                </template>
              </el-table-column>
              <el-table-column label="计划截止日期" prop="endDate" align="center">
                <template slot-scope="scope">
                  <el-date-picker v-if="PlanList[scope.$index].state==0"
                                  clearable
                                  v-model="scope.row.endDate"
                                  type="date"
                                  style="width: 100%;"
                                  value-format="yyyy-MM-dd"
                                  placeholder="请选择日期">
                  </el-date-picker>

                  <span v-else>{{scope.row.endDate}}</span>

                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
                <template slot-scope="scope">
                  <el-button v-if="PlanList[scope.$index].state==0" size="mini" type="text" icon="el-icon-edit" @click="submitForm(scope.$index)"
                             v-hasPermi="['mes:proinfo:edit']">下达</el-button>
                  <el-button v-else-if="PlanList[scope.$index].state==1" size="mini" type="text" icon="el-icon-delete" @click="handleWithdraw(scope.$index,scope.row)"
                             v-hasPermi="['mes:proinfo:remove']">撤回</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-form-item>

      </el-form>
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="submitForm">确 定</el-button>-->
<!--        <el-button @click="cancel">取 消</el-button>-->
<!--      </div>-->
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan, getPlanPro, addMatPlan,getReleasedPlan, updateMatPlan} from "@/api/mes/plan";
import {newAddMater_plan} from "@/api/mes/mater_plan";

export default {
  name: "Plan",
  dicts:["plan_state"],
  data() {
    return {
      counts:1,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      orderIds:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划表格数据
      planList: [],
      planProList: [],
      matPlanList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planSn: null,
        planState: null,
      },
      // 查询参数
      queryParamsPro: {
        proName: null,
        proType: null,
      },
      // 表单参数
      form: {},
      //计划下达表单
      PlanList:[
        {
          orderId:null,
          proId:null,
          num:0,
          planDate:null,
          startDate: null,
          endDate: null,
          state:0,
        }
      ],
      //定义Map
      planMap: new Map(),
      //定义Map
      buttonMap: new Map(),
      // 表单校验
      rules: {
        planSn: [
          { required: true, message: "主计划编号不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.planMap.set( 0,'已下达');
    this.planMap.set( 1,'部分下达');
    this.planMap.set( 2,'已撤回');
    this.planMap.set( 3,'未下达');
    this.buttonMap.set(0,'未下达');
    this.buttonMap.set(1,'已下达');
    this.buttonMap.set(2,'已撤回');
  },
  methods: {
    //改变按钮状态和新增行
    changeButton(index){
      if(this.PlanList[index].state==0)
      {
        this.PlanList[index].state=1;
        this.PlanList.splice(index+1,0,
          {
            orderId:null,
            proId:null,
            num:0,
            planDate:null,
            startDate: null,
            endDate: null,
            state:0
          }
        )
        console.log('this.PlanList1',this.PlanList)
        this.counts=this.counts+1;
      }
      else{
        this.PlanList[index].state=2;
      }

    },
    /** 查询生产计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.calculateIndex()
      });

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      // location.reload();
      this.PlanList.length=this.PlanList.length-this.counts
      this.counts=0
      this.PlanList.push(
        {
          orderId:null,
          proId:null,
          num:0,
          planDate:null,
          startDate: null,
          endDate: null,
          state:0
        }
      )
      console.log(this.PlanList)
      this.counts=this.counts+1;
    },
    /** 计算列表编号 */
    calculateIndex() {
      this.planList.forEach((item, index) => {
        this.$set(item, 'number', index + 1);
      });
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        proId: null,
        planSn: null,
        planState: null,
        reqNum: null,
        planNum: null,
        grNum: null,
        startDate: null,
        endDate: null,
        isDeleted: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedDate: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.orderIds = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加生产计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      const orderId = row.orderId || this.orderIds
      getPlanPro(orderId).then(response => {
        this.planProList = response.data;
        console.log("dadawww",this.planProList)
      });
      getReleasedPlan(orderId).then(response => {
        this.PlanList = response;
        console.log('reasdf',response)
        this.PlanList.splice( this.PlanList.length+1,0,
          {
            orderId:null,
            proId:null,
            num:0,
            planDate:null,
            startDate: null,
            endDate: null,
            state:0
          }
        );
        this.counts=1;
        this.open = true;
        this.title = "生产计划明细";
      });
    },
    /** 提交按钮 */
    submitForm(index) {
      // this.PlanList.length=this.PlanList.length-1
      console.log("PlanList",this.PlanList)
      const orderId = this.planProList[0].orderId
      this.PlanList[index].orderId=this.planProList[0].orderId;
      this.PlanList[index].state=1;
      addMatPlan(this.PlanList[index]).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  getReleasedPlan(orderId).then(response => {
                    this.matPlanList = response;
                    this.matPlanList[index].releasedId=this.matPlanList[index].id
                    newAddMater_plan(this.matPlanList[index]).then(response => {
                      this.$modal.msgSuccess("修改成功");
                    });
                  });
                  this.counts=this.counts-1;
                  this.PlanList[index].state=0;
                  this.changeButton(index);
                  this.getList();
                });
    },

    /** 撤回按钮操作 */
    handleWithdraw(index,row) {
      const id = row.id
      updateMatPlan(id).then(response =>{
        this.$modal.msgSuccess("撤回成功");
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const planSn = row.planSn || this.planSn;
      this.$modal.confirm('是否撤回生产计划编号为"' + planSn + '"的数据项？').then(function() {
        return delPlan(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤销成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
